package org.gosdt.ew.view;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import org.gosdt.ew.model.Languages;


public class LanguagesForm extends BaseForm {
	
	private JDialog myJDParent;
	private static final long serialVersionUID = 1L;
		
	private JLabel jlbNewLanguage = new JLabel();
	
	private JTextField jtfLanguageName = new JTextField(20);
	
	private JButton jbtSave = new JButton();
	private JButton jbtCancel = new JButton();
	
	private JPanel jpnAvailableActions = new JPanel(); // any common buttons
	private JPanel jpnAvailableSettings = new JPanel(null); // all other thing

	public LanguagesForm(JFrame parent, JDialog dialogParent){
		super(parent, "add new language");
		myJDParent = dialogParent;
		this.setLayout(new BorderLayout());
		doInitForm();
		this.setVisible(true);
	}
	@Override
	public void doInitForm() {
		int fWidth = this.getWidth();
		int large = fWidth - 10;
		int magic = 350; // count of pixel for good buttonany
		
		setLabelsName();
		
		this.add(jpnAvailableActions, BorderLayout.SOUTH);
		this.add(jpnAvailableSettings, BorderLayout.CENTER);
		
		jlbNewLanguage.setBounds(5,5, large, 25);
		jtfLanguageName.setBounds(5,30, large, 25);
		
		jpnAvailableSettings.add(jlbNewLanguage);
		jpnAvailableSettings.add(jtfLanguageName);
		
		if (fWidth <= magic){
			jbtCancel.setPreferredSize(new Dimension((int)(fWidth * 0.30), 25));
			jbtSave.setPreferredSize(new Dimension((int)(fWidth * 0.30), 25));
			jpnAvailableActions.setLayout(new FlowLayout(FlowLayout.CENTER, (int)(fWidth * 0.025), 0));
		}
		
		jpnAvailableActions.add(jbtCancel);
		jpnAvailableActions.add(jbtSave);
		
		setButtonListeners();
	}

	private void closeForm(){
		myParent.changeTimerStatus();
		jbtCancel.removeActionListener(jbtCancel.getActionListeners()[0]);
		jbtSave.removeActionListener(jbtSave.getActionListeners()[0]);
		this.dispose();
	}
	@Override
	protected void setButtonListeners() {
		jbtCancel.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				closeForm();
			}
		});
		
		jbtSave.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				Languages language = Languages.GetOneRowByName(jtfLanguageName.getText().trim().toLowerCase());
				language.insertCurRecord();
				((SettingsForm) myJDParent).setLanguageItems();
				closeForm();
			}
		});
					
	}

	@Override
	public void setLabelsName() {
		jlbNewLanguage.setText("Название языка");		
		jbtSave.setText("Сохранить");
		jbtCancel.setText("Закрыть");
	}

}
